package com.jappit.runtracker.utils;

import java.util.Vector;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;

public class AppUtils
{
	static AppUtils instance = null;
	
	MIDlet midlet;
	
	Vector screenHistory = null;
	
	Displayable currentScreen = null;
	
	public static AppUtils getInstance()
	{
		if(instance == null)
		{
			instance = new AppUtils();
		}
		return instance;
	}
	AppUtils()
	{
		screenHistory = new Vector();
	}
	public MIDlet getMIDlet()
	{
		return midlet;
	}
	
	public void setMIDlet(MIDlet midlet)
	{
		this.midlet = midlet;
	}
	public void exit()
	{
		midlet.notifyDestroyed();
	}
	public void gotoScreen(Displayable screen)
	{
		this.gotoScreen(screen, false);
	}
	public void gotoScreen(Displayable screen, boolean avoidHistory)
	{
		if(!avoidHistory && currentScreen != null)
			screenHistory.addElement(currentScreen);
		
		Display.getDisplay(midlet).setCurrent(screen);
		
		currentScreen = screen;
	}
	public void gotoInitialScreen()
	{
		while(screenHistory.size() > 1)
		{
			screenHistory.removeElement(screenHistory.lastElement());
		}
		gotoPreviousScreen();
	}
	public void gotoPreviousScreen()
	{
		if(screenHistory.size() > 0)
		{
			Displayable screen = (Displayable)screenHistory.lastElement();
			
			screenHistory.removeElement(screen);
			
			Display.getDisplay(midlet).setCurrent(screen);
			
			currentScreen = screen;
		}
	}
	public void showError(String text)
	{
    	Alert errorAlert = new Alert(text);
    	Display.getDisplay(midlet).setCurrent(errorAlert);
	}
}
